package com.wrxdz.start.surfaceviewt.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.wrxdz.start.surfaceviewt.ApplicationUtil;
import com.wrxdz.start.surfaceviewt.MainActivity;
import com.wrxdz.start.surfaceviewt.surfview.model.Person;
import com.wrxdz.start.surfaceviewt.surfview.utils.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Objects;

/**
 * 从服务器接收
 * handler:
 * 0 开始游戏
 * 1 结束游戏
 * 2 接收其他玩家出牌
 * 向服务器发送
 * recHandler:
 * 1 游戏结束
 * 2 发送自身出牌
 * <p>
 * android 编码方式utf-8
 * windows 编码方式utf-8(默认GBK)
 */
public class GameView extends AppCompatActivity {
    public static final String TAG = "GameActivity";
    private com.wrxdz.start.surfaceviewt.surfview.GameView sv;
    private int[] selfPukes = null;
    private int[] threePukes = null;
    private String[] userNames = null;
    private int selfNameIndex;
    //从服务器接收
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //对应UI动作更新
            switch (msg.what) {
                case 0:
                    Toast.makeText(GameView.this, "游戏开始", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(GameView.this, "有玩家胜利,游戏结束", Toast.LENGTH_SHORT).show();
                    //停止
                    break;
                case 2:
                    String s = msg.obj.toString();
                    //更新上一次出牌及玩家名称
                    sv.receiveServerToUpdate(s);
                    break;

            }
            return true;
        }
    });

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: 被调用");
        // 这个是隐藏标题栏，不解释
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        Objects.requireNonNull(getSupportActionBar()).hide();
        // 隐藏状态栏，你懂的
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        /*
         * 开始有考虑使屏幕上扑克的排列随屏幕的分辨率变动 结果貌似不好做，注释掉了 Display display =
         * getWindowManager().getDefaultDisplay(); int screenWidth =
         * display.getWidth(); int screenHeight = display.getHeight();
         */
        // 使用代码锁定横屏
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        ApplicationUtil applicationUtil = (ApplicationUtil) getApplication();
        if (!applicationUtil.isConnect()) {
            Intent intent = new Intent(GameView.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        //获取初始化数据
        initData();
        //连接服务器
        final ClientThread clientThread = new ClientThread(applicationUtil.getSocket(), handler);
        new Thread(clientThread).start();
        sv = new com.wrxdz.start.surfaceviewt.surfview.GameView(this, selfPukes, threePukes,userNames,selfNameIndex);
        //把handler设置view中
        sv.setHandler(clientThread.getHandler());
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);这个是竖屏
        setContentView(sv);
//        setContentView(R.layout.activity_game_view);

//        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
//
//        int width = wm.getDefaultDisplay().getWidth();
//        int height = wm.getDefaultDisplay().getHeight();
//        Toast.makeText(this,width+","+height,Toast.LENGTH_LONG).show();
    }

    //获取数据
    private void initData() {
        Intent intent = getIntent();
        selfPukes = intent.getIntArrayExtra("selfPukes");
        threePukes = intent.getIntArrayExtra("threePukes");
        userNames = intent.getStringArrayExtra("allUserName");
        selfNameIndex = intent.getIntExtra("selfNameIndex",-1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: 被调用");
        ((ApplicationUtil) getApplication()).closeSocket();
    }

}

class ClientThread implements Runnable {
    private Handler handler;
    private Handler recHandler;
    private BufferedReader bufferedReader;
    private OutputStream outputStream;
    private Socket socket;

    ClientThread(Socket socket, Handler handler) {
        this.handler = handler;
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            outputStream = socket.getOutputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //启动一条线程接受服务器消息通知
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String content;
                    try {
                        while ((content = bufferedReader.readLine()) != null) {
                            //对content进行解析
                            switch (content) {
                                case "游戏开始":
                                    handler.sendEmptyMessage(0);
                                    break;
                                case "游戏正常结束":
                                    handler.sendEmptyMessage(1);
                                    break;
                                default:
                                    Message message = new Message();
                                    message.what = 2;
                                    message.obj = content;
                                    handler.sendMessage(message);
                                    break;
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            Looper.prepare();
            //向服务器发送
            recHandler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    switch (msg.what) {
                        //游戏结束
                        case 1:
                            handler.sendEmptyMessage(1);
                            try {
                                outputStream.write(("游戏正常结束" + "\r\n").getBytes("utf-8"));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            break;
                        //出牌
                        case 2:
                            try {
                                outputStream.write((msg.obj.toString() + "\r\n").getBytes("utf-8"));
                                Log.i(GameView.TAG, "handleMessage: " + msg.obj.toString());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            break;
                    }
                    return true;
                }
            });
            Looper.loop();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Handler getHandler() {
        return recHandler;
    }
}
